<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="插件名" prop="pluginsFileName">
        <el-input
          v-model="queryParams.pluginsFileName"
          placeholder="请输入插件名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传时间" prop="uploadTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.uploadTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择上传时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:plugins:add']"
        >上传</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:plugins:remove']"
        >批量删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pluginsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="pluginsSortId" />
<!--      <el-table-column label="插件ID" align="center" prop="pluginsFileId" />-->
<!--      <el-table-column label="插件地址" align="center" prop="pluginsFileAddress" />-->
      <el-table-column label="插件名" align="center" prop="pluginsFileName" />
      <el-table-column label="大小(Byte)" align="center" prop="pluginsFileSize" />
      <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:plugins:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDown(scope.row)"
            v-hasPermi="['system:plugins:remove']"
          >下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改插件管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>

      <el-upload
        ref="upload"
        :limit="100"
        accept=".jar"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入jar格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPlugins, getPlugins, delPlugins, addPlugins, updatePlugins } from "@/api/system/plugins";
import {getToken} from "@/utils/auth";
import axios from "axios";
import {blobValidate} from "@/utils/ruoyi";
import { saveAs } from 'file-saver'

export default {
  name: "userPlugins",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 插件管理表格数据
      pluginsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pluginsSortId: null,
        pluginsFileAddress: null,
        pluginsFileName: null,
        pluginsFileSize: null,
        uploadTime: null
      },
      // 用户上传参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/uploadjarfile", // 上传的文件服务器地址
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        pluginsSortId: [
          { required: true, message: "序号不能为空", trigger: "blur" }
        ],
        pluginsFileSize: [
          { required: true, message: "大小(Byte)不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询插件管理列表 */
    getList() {
      this.loading = true;
      listPlugins(this.queryParams).then(response => {
        this.pluginsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        pluginsFileId: null,
        pluginsSortId: null,
        pluginsFileAddress: null,
        pluginsFileName: null,
        pluginsFileSize: null,
        uploadTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.pluginsFileId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 上传按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "上传插件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const pluginsFileId = row.pluginsFileId || this.ids
      getPlugins(pluginsFileId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改插件管理";
      });
    },
    /** 下载按钮操作 */
    handleDown(row) {
      this.downloadFile(row.pluginsFileName, row.pluginsFileAddress);
    },
    downloadFile(fileName, filePath){
      const baseURL = process.env.VUE_APP_BASE_API
      var url = baseURL + "/common/downloadjarfile?fileName=" + encodeURI(fileName) + "&filePath=" + encodeURI(filePath)
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: { 'Authorization': 'Bearer ' + getToken() }
      }).then(async (res) => {
        const isLogin = await blobValidate(res.data);
        if (isLogin) {
          const blob = new Blob([res.data])
          this.saveAs(blob, decodeURI(res.headers['download-filename']))
        }
      })
    },
    saveAs(text, name, opts) {
      saveAs(text, name, opts);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.pluginsFileId != null) {
            updatePlugins(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlugins(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const pluginsFileIds = row.pluginsFileId || this.ids;
      this.$modal.confirm('是否确认删除插件？').then(function() {
        return delPlugins(pluginsFileIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/plugins/export', {
        ...this.queryParams
      }, `plugins_${new Date().getTime()}.xlsx`)
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;

    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "上传结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
